package com.lw.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.lw.yygh.oss.service.FileService;
import com.lw.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        //上传至阿里云然后存储到数据库
        String baseUrl="https://yygh-lw.oss-cn-hangzhou.aliyuncs.com/";

        //设置请求头
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType( "image/jpg" );
        //创建OSSClient
        OSS oss = new OSSClientBuilder().build( ConstantOssPropertiesUtils.EDNPOINT, ConstantOssPropertiesUtils.ACCESS_KEY_ID, ConstantOssPropertiesUtils.SECRECT );
        //上传文件流

        try {
            InputStream inputStream=file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            //使用uuid
            String uuid = UUID.randomUUID().toString().replaceAll( "-", "" ).substring( 0, 6 );
            originalFilename=uuid+originalFilename;
            //按照当前日期，创建文件夹，上传到创建的文件夹里
            String timeUrl = new DateTime().toString( "yyyy/MM/dd" );
            originalFilename=timeUrl+"/"+originalFilename;
            oss.putObject( ConstantOssPropertiesUtils.BUCKET,originalFilename,inputStream ,objectMetadata);
            //返回文件路径
            return baseUrl+originalFilename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            oss.shutdown();
        }

    }
}
